<?php
namespace app\index\controller;

use app\index\controller\BaseController;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;


use WeChatPay\Crypto\Rsa;
use WeChatPay\Crypto\AesGcm;
use WeChatPay\Formatter;

class Notify extends BaseController
{
	public function wxpay(){
		$testxml  = file_get_contents("php://input");
		$result = json_decode($testxml, true);//转成数组，
		$info = Request::header();
		$inWechatpaySignature = $info['wechatpay-signature'];// 请根据实际情况获取
		$inWechatpayTimestamp = $info['wechatpay-timestamp'];// 请根据实际情况获取
		$inWechatpaySerial = $info['wechatpay-serial'];// 请根据实际情况获取
		$inWechatpayNonce = $info['wechatpay-nonce'];// 请根据实际情况获取
		if (!$inWechatpaySignature) {
		    //重定向浏览器
		    header("Location:/404.html");
		    //确保重定向后，后续代码不会被执行
		    exit;
		}
		$inBody = $testxml;// 请根据实际情况获取，例如: file_get_contents('php://input');
        $config=Db::name('mall_config')->column('value','key');
		$apiv3Key = $config['wx_v3_secret'];// 在商户平台上设置的APIv3密钥
		$platformPublicKeyInstance = Rsa::from(file_get_contents(env('root_path').'zhengshu/weixin/cert.pem'), Rsa::KEY_TYPE_PUBLIC);
		// 检查通知时间偏移量，允许50分钟之内的偏移
		$timeOffsetStatus = 3000 >= abs(Formatter::timestamp() - (int)$inWechatpayTimestamp);
		$verifiedStatus = Rsa::verify(
		    // 构造验签名串
		    Formatter::joinedByLineFeed($inWechatpayTimestamp, $inWechatpayNonce, $inBody),
		    $inWechatpaySignature,
		    $platformPublicKeyInstance
		);
		Log::write($timeOffsetStatus, 'lizhili78912');
		Log::write($verifiedStatus, 'lizhili78912');
		if ($timeOffsetStatus && $verifiedStatus) {
		    // 转换通知的JSON文本消息为PHP Array数组
		    $inBodyArray = (array)json_decode($inBody, true);
		    // 使用PHP7的数据解构语法，从Array中解构并赋值变量
		    ['resource' => [
		        'ciphertext'      => $ciphertext,
		        'nonce'           => $nonce,
		        'associated_data' => $aad
		    ]] = $inBodyArray;
		    // 加密文本消息解密
		    $inBodyResource = AesGcm::decrypt($ciphertext, $apiv3Key, $nonce, $aad);
		    // 把解密后的文本转换为PHP Array数组
		    $inBodyResourceArray = (array)json_decode($inBodyResource, true);
			Log::write($inBodyResourceArray, 'lizhili7891');
		    // print_r($inBodyResourceArray);// 打印解密后的结果
			$result=$inBodyResourceArray;
			if ($result['trade_state'] == 'SUCCESS') {
			    $out_trade_no = 'zong_'.$result['out_trade_no'];
				
				if($gu=Db::name('order')->where('out_trade_no', $out_trade_no)->where('pay_status', 0)->find()){
					
					Db::name('order')->where('id',$gu['id'])->update([
					    'pay_status'=>1,
					    'order_time'=>time(),
					    'pay_price'=>$result['amount']['payer_total']/100,
					]);

					return \json([
					      "code"=> "SUCCESS",
					        "message"=> "成功"
					   ]);
				}
			}
		}
		die;
	}


    public function alipay() //这个是阿里 的回调
    {
        $data=input('post.');
        Log::write($data, 'debug');
        require_once "aop/AopCertClient.php";
		$alipayCertPath = env('root_path')."zhengshu/alipayCertPublicKey_RSA2.crt";
        $aop = new \AopCertClient;
		 $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);
        $flag = $aop->rsaCheckV1($data, null, "RSA2");
        Log::write($flag, 'debug');
        if ($flag) {
            $order = Db::name('order')->where('out_trade_no', $data['out_trade_no'])->find();
            Log::write($order, 'debug');
            if ($order) {
                $fen=Db::name('order')->where('id', $order['id'])->where('pay_status', 0)->update([
                'pay_status'=>1,
                'pay_price'=>$data['buyer_pay_amount'],//支付的金额
                'order_time'=>time(),
                'notify_id'=>$data['notify_id'],
                'trade_no'=>$data['trade_no'],
              ]);
                echo 'success';
            } else {
                echo 'fail';
            }
        } else {
            echo 'fail';
        }
    }
}
